package com.ysh.xiaomi.service.impl;

import com.ysh.xiaomi.dao.AddressDao;
import com.ysh.xiaomi.dao.CartDao;
import com.ysh.xiaomi.dao.OrderDao;
import com.ysh.xiaomi.dao.impl.AddressDaoImpl;
import com.ysh.xiaomi.dao.impl.CartDaoImpl;
import com.ysh.xiaomi.dao.impl.OrderDaoImpl;
import com.ysh.xiaomi.pojo.CartDto;
import com.ysh.xiaomi.pojo.TbGoods;
import com.ysh.xiaomi.pojo.TbOrder;
import com.ysh.xiaomi.service.OrderService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 袁胜虎 on 2022/8/18 19:38
 */
public class OrderServiceImpl implements OrderService {
    OrderDao orderDao = new OrderDaoImpl();
    CartDao cartDao = new CartDaoImpl();
    AddressDao addressDao = new AddressDaoImpl();
    @Override
    public Map createOrder(Long userId, Long addressId, CartDto cartDto) {
        long sum = 0;
        for (int i = 0; i <cartDto.getGoodsList().size() ; i++) {
            //拿到每一件商品的价格和数量进行计算
            sum += cartDto.getGoodsList().get(i).getPrice()*cartDto.getNums()[i];
        }
        //1  生成一个订单的id,然后加上地址的id,用户的id,计算出商品的总价格,然后将数据插入到订单表中
        String orderId = UUID.randomUUID().toString().replace("-","");
        orderDao.addOrder(orderId,userId,addressId,sum);
        //利用上面生成的订单的id,和购物车中每一条数据,生成每一条订单详情单数据,也就是订单和商品之间的中间表的数据,插入到中间表中
        for (int i = 0; i <cartDto.getGoodsList().size() ; i++) {
            //将每一条商品的信息插入到数据库
            TbGoods tbGoods = cartDto.getGoodsList().get(i);
            orderDao.addOrderDetail(orderId,tbGoods.getKzid(),cartDto.getNums()[i],tbGoods.getPrice()*cartDto.getNums()[i]);
        }
        //返回结果
        //清理购物车
        cartDao.clearCart(userId);
        //返回结果的map
        HashMap<String,Object>resultMap = new HashMap<>();
        resultMap.put("id",orderId);
        resultMap.put("money",sum);
        return resultMap;
    }

    @Override
    public List<TbOrder> findByUserId(Long userId) {
        //先查询订单
        List<TbOrder> orderList =orderDao.findByUserId(userId);
        //查询每个订单关联的地址
        orderList.forEach(tbOrder -> {
            //获取到每一地址的id
//            Long aid = tbOrder.getAid();
//            //获取到地址
//            TbAddress address = addressDao.findById(aid);
//            tbOrder.setAddress(address);
            tbOrder.setAddress(addressDao.findById(tbOrder.getAid()));
        });
        return orderList;
    }

    @Override
    public int updateOrderStatus(String oid, String status) {
        return orderDao.updateOrderStaus(oid,status);
    }

    @Override
    public TbOrder findById(String orderId) {
        return orderDao.findById(orderId);
    }

    @Override
    public TbOrder findOrderById(String oid) {
        return  orderDao.findOrderById(oid);
    }
}
